package com.todod.service.impl;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.entity.QueryEntry;
import com.todod.mapper.MdTemplateMapper;
import com.todod.model.MdTemplate;
import com.todod.service.IMdTemplateService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsh
 * @since 2020-11-23
 */
@Service
@Transactional
public class MdTemplateServiceImpl extends ServiceImpl<MdTemplateMapper, MdTemplate> implements IMdTemplateService {
	@Autowired
	private MdTemplateMapper mdTemplateMapper;

	@Override
	public IPage<MdTemplate> getListPage(Long _userId, QueryEntry queryEntry) {

		Page<MdTemplate> page = new Page<>(queryEntry.getPage(), queryEntry.getLimit());
		IPage<MdTemplate> iPage = mdTemplateMapper.getListPage(page, queryEntry);

		return iPage;
	}

	@Override
	public void saveData(Long _userId, MdTemplate mdTemplate) {

		mdTemplate.setId(SnowflakeIdGenerator.getId());

		mdTemplate.setState("1");
		mdTemplate.setCreateTime(LocalDateTime.now());
		mdTemplate.setCreateUserId(_userId);
		mdTemplateMapper.insert(mdTemplate);
	}

	@Override
	public void editData(Long _userId, MdTemplate mdTemplate) {

		mdTemplate.setModifyTime(LocalDateTime.now());
		mdTemplate.setModifyUserId(_userId);
		mdTemplateMapper.updateById(mdTemplate);
	}

	@Override
	public void updateState(Long _userId, Long code, String status) {
		MdTemplate mdTemplate = mdTemplateMapper.selectById(code);

		mdTemplate.setState(status);
		mdTemplate.setModifyUserId(_userId);
		mdTemplate.setModifyTime(LocalDateTime.now());
		mdTemplateMapper.updateById(mdTemplate);
	}

	@Override
	public MdTemplate getByDefaultDataByType(String type, Long departid) {
		QueryWrapper<MdTemplate> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mt_type", type);
		queryWrapper.eq("mt_department_id", departid);

		MdTemplate mdTemplate = mdTemplateMapper.selectOne(queryWrapper);
		return mdTemplate;
	}

	@Override
	public void onDefault(Long _userId, Long code) {
		MdTemplate mdTemplate = mdTemplateMapper.selectById(code);

		mdTemplate.setDefaultData(1l);
		mdTemplate.setModifyUserId(_userId);
		mdTemplate.setModifyTime(LocalDateTime.now());
		mdTemplateMapper.updateById(mdTemplate);
	}

}
